import request from './config'
import { showToast } from 'vant'

// 图片服务器地址
const IMAGE_SERVER_URL = import.meta.env.VITE_IMAGE_SERVER_URL

// 客户类型定义
export interface Customer {
  id: string;
  buyerName: string; // 对应后端 buyerName
  contact: string;   // 对应后端 contact
  image: string;     // 对应后端 image
  address?: string;
  notes?: string;
  orderCount?: number;
  totalAmount?: number;
  lastVisit?: string;
  avatarIndex?: number;
}

// 分页结果接口
export interface PageResult<T> {
  records: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

// 映射后端返回的数据到前端使用的格式
const mapCustomerData = (data: any): Customer => {
  return {
    id: data.id,
    buyerName: data.buyerName || '',
    contact: data.contact || '',
    image: data.image ? `${IMAGE_SERVER_URL}` + request.defaults.baseURL + `/file/download/${data.image}` : '',
    address: data.address,
    notes: data.notes,
    orderCount: data.orderCount || 0,
    totalAmount: data.totalAmount,
    lastVisit: data.lastVisit,
    avatarIndex: data.avatarIndex
  }
}

// 获取客户列表（分页）
export const getCustomerList = async (
  keyword?: string, 
  pageNum: number = 1, 
  pageSize: number = 10
) => {
  try {
    // 使用POST方法，后端使用@RequestBody接收参数
    const response = await request.post('/buyer/pageBuyers', {
      pageNum, 
      pageSize,
      buyerName: keyword // 使用buyerName作为搜索参数
    })
    
    console.log('客户列表API响应:', response)
    
    // 后端返回结构：{ code, msg, data: { records, total, size, current, pages } }
    if (response && response.data && response.data.code === 200 && response.data.data) {
      const pageData = response.data.data;
      return {
        records: Array.isArray(pageData.records) ? pageData.records.map(mapCustomerData) : [],
        total: pageData.total || 0,
        size: pageData.size || pageSize,
        current: pageData.current || pageNum,
        pages: pageData.pages || 0
      } as PageResult<Customer>
    }
    
    console.error('获取客户列表失败:', response?.data?.msg || '未知错误')
    showToast(response?.data?.msg || '获取客户列表失败')
    return {
      records: [],
      total: 0,
      size: pageSize,
      current: pageNum,
      pages: 0
    } as PageResult<Customer>
  } catch (error) {
    console.error('获取客户列表失败:', error)
    showToast('获取客户列表失败')
    return {
      records: [],
      total: 0,
      size: pageSize,
      current: pageNum,
      pages: 0
    } as PageResult<Customer>
  }
}

// 获取客户详情
export const getCustomerDetail = async (id: string) => {
  try {
    const response = await request.post('/buyer/getBuyerById', null, {
      params: { id }
    })
    if (response && response.data && response.data.code === 200 && response.data.data) {
      return mapCustomerData(response.data.data)
    }
    console.error('获取客户详情失败:', response?.data?.msg || '未知错误')
    showToast(response?.data?.msg || '获取客户详情失败')
    throw new Error(response?.data?.msg || '获取客户详情失败')
  } catch (error) {
    console.error('获取客户详情失败:', error)
    showToast('获取客户详情失败')
    throw error
  }
}

// 创建新客户
export const createCustomer = async (customer: Omit<Customer, 'id'>) => {
  try {
    // 创建 FormData 对象
    const formData = new FormData()
    
    // 添加买家基本信息
    const buyer = {
      buyerName: customer.buyerName,
      contact: customer.contact || ''
    }
    formData.append('buyer', new Blob([JSON.stringify(buyer)], { type: 'application/json' }))

    // 如果有图片数据（base64），转换为文件
    if (customer.image && customer.image.startsWith('data:image')) {
      const imageFile = await base64ToFile(customer.image, 'avatar.png')
      formData.append('imageFile', imageFile)
    }

    const response = await request.post('/buyer/addBuyer', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response && response.data && response.data.code === 200) {
      showToast('创建客户成功')
      return response.data.data ? mapCustomerData(response.data.data) : null
    }
    console.error('创建客户失败:', response?.data?.msg || '未知错误')
    showToast(response?.data?.msg || '创建客户失败')
    throw new Error(response?.data?.msg || '创建客户失败')
  } catch (error) {
    console.error('创建客户失败:', error)
    showToast('创建客户失败')
    throw error
  }
}

// base64 转 File 工具函数
const base64ToFile = async (base64Str: string, filename: string): Promise<File> => {
  const res = await fetch(base64Str)
  const blob = await res.blob()
  return new File([blob], filename, { type: blob.type })
}

// 更新客户信息
export const updateCustomer = async (id: string, customer: Partial<Customer>) => {
  try {
    // 创建 FormData 对象
    const formData = new FormData()

    const customerData = {
      id,
      buyerName: customer.buyerName,
      contact: customer.contact,
      image: customer.image,
      address: customer.address,
      notes: customer.notes
    }
    formData.append('buyer', new Blob([JSON.stringify(customerData)], { type: 'application/json' }))

    // 如果有图片数据（base64），转换为文件
    if (customer.image && customer.image.startsWith('data:image')) {
      const imageFile = await base64ToFile(customer.image, 'avatar.png')
      formData.append('imageFile', imageFile)
    }

    const response = await request.post('/buyer/updateBuyer', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response && response.data && response.data.code === 200) {
      showToast('更新客户信息成功')
      return response.data.data ? mapCustomerData(response.data.data) : null
    }
    
    console.error('更新客户信息失败:', response?.data?.msg || '未知错误')
    showToast(response?.data?.msg || '更新客户信息失败')
    throw new Error(response?.data?.msg || '更新客户信息失败')
  } catch (error) {
    console.error('更新客户信息失败:', error)
    showToast('更新客户信息失败')
    throw error
  }
}

// 删除客户
export const deleteCustomer = async (id: string) => {
  try {
    const response = await request.post('/buyer/deleteBuyer', null, {
      params: { id }
    })
    if (response && response.data && response.data.code === 200) {
      showToast('删除客户成功')
      return true
    }
    console.error('删除客户失败:', response?.data?.msg || '未知错误')
    showToast(response?.data?.msg || '删除客户失败')
    throw new Error(response?.data?.msg || '删除客户失败')
  } catch (error) {
    console.error('删除客户失败:', error)
    showToast('删除客户失败')
    throw error
  }
} 